package ebj.common.mail;

import java.util.List;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;


public class EMail {
	private static final Logger logger = LoggerFactory.getLogger(EMail.class);

	public final static String HOST = "appmail.sh.ctriptravel.com";
	public final static String USER = "appmail051";
	public final static String PASSWORD = "b9{jkJ8^A\"iJ)B^wxem!";
	public final static String FROM = "adhoc_service@ctrip.com";
	
	/**
	 * 邮件发送，收件人列表为： xxx_1@Ctrip.com[;xxx_n@Ctrip.com] String
	 * @param subject 邮件主题
	 * @param content 邮件内容
	 * @param mails	收件人列表 xxx_1@Ctrip.com[;xxx_n@Ctrip.com]
	 * @param cc 抄送收件人列表 xxx_1@Ctrip.com[;xxx_n@Ctrip.com]
	 * @throws MessagingException
	 */
	public static void sendMail(String subject, String content, String mails,
			String cc) throws MessagingException {

		InternetAddress[] toList = getMailList(mails);
		InternetAddress[] ccList = getMailList(cc);
		
		send(subject, content, toList, ccList);
	}

	
	/**
	 * 邮件发送，收件人列表为： userName List
	 * @param subject
	 * @param content
	 * @param mails
	 * @param ccs
	 * @return
	 * @throws MessagingException
	 */
	public static int sendMail(String subject, String content, List<String> mails,
			List<String> ccs ) throws MessagingException {
		
		if(mails == null || mails.size() == 0 ) return 1 ;
		
		List<String> toTmpList = Lists.newArrayList();
		for (String to : mails) {	
			if(Strings.isNullOrEmpty(to)) continue;				
			toTmpList.add(tansferUsrName2Mail(to));					
		}
		
		List<String> ccTmpList = Lists.newArrayList();
		if(ccs != null && ccs.size() >0 ) {
			for (String cc : ccs) {	
				if(Strings.isNullOrEmpty(cc)) continue;				
				ccTmpList.add(tansferUsrName2Mail(cc));
			}
		}

		InternetAddress[] toList = getMailList(Joiner.on(";").join(toTmpList));
		InternetAddress[] ccList2 = getMailList(Joiner.on(";").join(ccTmpList));
		
		send(subject, content, toList, ccList2);

		return 0;
	}

	/**
	 * @param mails 取值 xxx_1@Ctrip.com[;xxx_n@Ctrip.com]
	 * @return
	 */
	private static InternetAddress[] getMailList(String mails) {
		if (mails == null) {
			return null;
		}
		String[] toMails = mails.split(";");
		InternetAddress[] addresses = new InternetAddress[toMails.length];
		try {
			for (int i = 0; i < toMails.length; i++) {
				addresses[i] = new InternetAddress(toMails[i].trim());
			}
		} catch (AddressException e) {
			logger.error("The email address error, Ignore! Error msg:", e);
		}
		return addresses;
	}
	
	private static String tansferUsrName2Mail(String usrName) {
		String MAIL_SUFFEX = "@Ctrip.com";
		return (usrName.indexOf(MAIL_SUFFEX) == -1) ? (usrName + MAIL_SUFFEX) : usrName;
	}

	/**
	 * 发送执行
	 * @param subject
	 * @param content
	 * @param toList
	 * @param ccList
	 * @throws MessagingException
	 * @throws AddressException
	 * @throws NoSuchProviderException
	 */
	private static void send(String subject, String content,
			InternetAddress[] toList, InternetAddress[] ccList) throws MessagingException, AddressException, NoSuchProviderException {
		Properties props = new Properties();
		props.put("mail.smtp.host", HOST);
		props.put("mail.smtp.starttls.enable", "true");
		// props.put("mail.smtp.port", "25");
		props.put("mail.smtp.auth", "true");
		// props.put("mail.debug", "true");
		Session mailSession = Session.getInstance(props, new MyAuthenticator());

		Message message = new MimeMessage(mailSession);
		message.setFrom(new InternetAddress(FROM));
		message.addRecipients(Message.RecipientType.TO, toList);
		message.addRecipients(Message.RecipientType.CC, ccList);

		message.setSubject(subject);
		message.setContent(content, "text/html;charset=utf-8");

		Transport transport = mailSession.getTransport("smtp");
		try {
			transport.connect(HOST, USER, PASSWORD);
			transport.sendMessage(message, message.getAllRecipients());
		} finally {
			if (transport != null)
				transport.close();
		}
	}
}

class MyAuthenticator extends Authenticator {
	@Override
	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(EMail.USER, EMail.PASSWORD);
	}
}